<template>
  <vue-seamless-scroll :data="tableData" :class-option="scrollOption">
    <el-table
      :data="tableData"
      :show-header="false"
      stripe
      style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column v-for="col in columns" :key="col.prop" v-bind="col" />
      <el-table-column width="120" v-if="showTodo">
        <template #default="scope">
          <el-link @click="$emit('detail', scope.row)">查看详情</el-link>
        </template>
      </el-table-column>
    </el-table>
  </vue-seamless-scroll>
</template>

<script>
import vueSeamlessScroll from 'vue-seamless-scroll';

export default {
  name: "AutoScrollTable",
  components: {
    vueSeamlessScroll
  },
  props: {
    fetchData: {
      type: Function,
      required: true, // (page, pageSize) => Promise<Array>
    },
    showTodo: {
      type: Boolean,
      default: true
    },
    columns: {
      type: Array,
      required: true, // [{ prop: 'name', label: '名称', width: 100 }, ...]
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    scrollOption: {
      type: Object,
      default: () => ({
        step: 0.2, // 数值越大速度滚动越快
        limitMoveNum: 2, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
      }),
    },
  },
  data() {
    return {
      tableData: [],
      pageNum: 1,
      loading: false,
      finished: false,
    };
  },
  mounted() {
    this.loadMore();
    // this.initScrollCheck();
  },
  methods: {
    async loadMore() {
      if (this.loading || this.finished) return;
      this.loading = true;
      try {
        const newData = await this.fetchData(this.pageNum, this.pageSize);
        if (newData.length < this.pageSize) this.finished = true;
        this.tableData = [...this.tableData, ...newData];
        this.pageNum++;
      } finally {
        this.loading = false;
      }
    },
    initScrollCheck() {
      this.$nextTick(() => {
        const wrapper = this.$el.querySelector('.el-table__body-wrapper');
        if (!wrapper) return;
        setInterval(() => {
          const scrollBottom = wrapper.scrollHeight - wrapper.scrollTop - wrapper.clientHeight;
          if (scrollBottom < 10) {
            this.loadMore();
          }
        }, 1000);
      });
    },
  },
};
</script>
